package movee.utils.crypto;

import org.apache.commons.io.FileUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public final class ZipUtils {

    private ZipUtils() { }

    public static byte[] zipFiles(String zipDir, List<File> fileList) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try (ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream)) {
            // 先创建一个文件夹
            ZipEntry folderEntry = new ZipEntry(zipDir + File.separator);
            zipOutputStream.putNextEntry(folderEntry);
            for (int i = 0; i < fileList.size(); i++) {
                // 把文件放入到文件夹中
                File file = fileList.get(i);
                if (file.exists()) {
                    String fileName = file.getName();
                    // 创建一个条目
                    ZipEntry zipEntry = new ZipEntry(zipDir + File.separator + fileName);
                    // 创建一个条目添加到zip中
                    zipOutputStream.putNextEntry(zipEntry);
                    byte[] bytes = FileUtils.readFileToByteArray(file);
                    zipOutputStream.write(bytes, 0, bytes.length);
                    zipOutputStream.closeEntry();
                }
            }
            // 当前目录写完了
            zipOutputStream.closeEntry();
        }
        return outputStream.toByteArray();
    }

}
